package com.coocaa.x.demo.servlets;

import android.os.RemoteException;

import com.coocaa.x.demo.servlets.data.ParserData;
import com.coocaa.x.demo.servlets.data.ParserData.AppDetailObject;
import com.coocaa.x.demo.servlets.data.ParserData.AppListObject;
import com.coocaa.x.demo.servlets.data.WebDataDB;
import com.coocaa.x.demo.servlets.parser.JsonParser;
import com.coocaa.x.demo.servlets.utils.DownloadListener;
import com.coocaa.x.demo.servlets.utils.FileDownload;
import com.coocaa.x.framework.utils.AsyncTask;
import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.service.XServiceManager;
import com.coocaa.x.service.litedb.data.client.LiteDBSupport;
import com.coocaa.x.service.litepm.data.InstallParams;
import com.coocaa.x.service.litewebserver.webserver.LiteWebHttpd;
import com.coocaa.x.service.litewebserver.webserver.NanoHTTPD;
import com.coocaa.x.service.litewebserver.webserver.cache.ImageCache;
import com.coocaa.x.service.litewebserver.webserver.servlet.Servlet;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//import com.coocaa.x.demo.servlets.data.ParserData.AppCategory;
//import com.coocaa.x.demo.servlets.data.ParserData.AppCategory.AppCategoryItem;
//import com.coocaa.x.demo.servlets.data.ParserData.AppCategory.AppCategoryItem.SubSortItem;
//import com.coocaa.x.demo.servlets.data.ParserData.AppDetailObject.AppDetailItem;
//import com.coocaa.x.demo.servlets.data.ParserData.AppListObject.AppListItem;
//import com.coocaa.x.demo.servlets.data.ParserData.CategoryObject;
//import com.coocaa.x.demo.servlets.data.ParserData.CategoryObject.CategoryItem;
//import com.coocaa.x.demo.servlets.data.ParserData.SubCategoryObject;
//import com.coocaa.x.demo.servlets.data.ParserData.SubCategoryObject.SubCategoryItem;
//import com.coocaa.x.demo.servlets.data.ParserData.SubCategoryObject.SubCategoryItem.FiltersItem;
//import com.coocaa.x.demo.servlets.data.ParserData.VideoDetailObject;
//import com.coocaa.x.demo.servlets.data.ParserData.VideoDetailObject.VideoDetail;
//import com.coocaa.x.demo.servlets.data.ParserData.VideoListObject;
//import com.coocaa.x.demo.servlets.data.ParserData.VideoListObject.VideoItem;
//import com.coocaa.x.demo.servlets.data.ParserData.VideoSearch;
//import com.coocaa.x.demo.servlets.data.ParserData.VideoSearch.VideoSearchList;
//import com.coocaa.x.demo.servlets.data.ParserData.VideoSearch.VideoSearchList.FromItem;

/**
 * Created by admin on 2015/9/10.
 */
public class WebDataServlet extends Servlet implements DownloadListener {
    private static final String tag = "webdata";
    private ServletInfo info = null;
    private HashMap<String,Object> cache = new HashMap<String,Object>();
//    private SessionHandler handlers = null;

    @Override
    protected void onCreate() {
        getSessionHandler().addHandler("/getVideoCategory", videoCategoryHandler);
        getSessionHandler().addHandler("/getFilterConditionsList", videoSubCategoryHandler);
        getSessionHandler().addHandler("/getVideoListByFilterId", videoListHandler);
        getSessionHandler().addHandler("/getVideoDetail", videoDetailHandler);
        getSessionHandler().addHandler("/getVideoListByKeyWord", videoSearchHandler);

        getSessionHandler().addHandler("/getAppCategory", appCategoryHandler);
        getSessionHandler().addHandler("/getAppList", appListHandler);
        getSessionHandler().addHandler("/getAppDetail", appDetailHandler);
        getSessionHandler().addHandler("/downloadApp", appDownloadHandler);
        getSessionHandler().addHandler("/searchApp", searchAppHandler);
    }

    @Override
    protected void onDestroy() {
    }

    @Override
    protected NanoHTTPD.Response onServe(NanoHTTPD.IHTTPSession session) {
        return getSessionHandler().handle(session);
    }

    @Override
    public ServletInfo getServletInfo() {
        if (info == null) {
            info = new ServletInfo();
            info.vendorName = "superx";
            info.servletName = "webdata";
            info.versionCode = 1;
            info.versionName = "1.0.0";
        }
        return info;
    }

    @Override
    protected InputStream getResource(String uri) {
        return null;
    }

    private LiteWebHttpd.ServletHandler videoCategoryHandler = new LiteWebHttpd.ServletHandler(){

        @Override
        public NanoHTTPD.Response serve(NanoHTTPD.IHTTPSession session) {
            NanoHTTPD.Response r;
            LogUtils.d(tag, "videoCategoryHandler  param:" + session.getUri());
            String url = "http://video.tc.skysrt.com/c/getVideoCategory";
            String json = JsonParser.getJsonFromWeb(url);
            LogUtils.d(tag,"videoCategoryHandler json:"+json);
            return newFixedLengthResponse(json);
        }
    };

    private LiteWebHttpd.ServletHandler videoSubCategoryHandler = new LiteWebHttpd.ServletHandler(){

        @Override
        public NanoHTTPD.Response serve(NanoHTTPD.IHTTPSession session) {
            NanoHTTPD.Response r;
            String param = session.getQueryParameterString();
            LogUtils.d(tag,"videoSubCategoryHandler  param:"+param);
            String url = "http://video.tc.skysrt.com/c/getFilterConditionsList?"+param;
            String json = JsonParser.getJsonFromWeb(url);
            LogUtils.d(tag,"videoSubCategoryHandler json:"+json);
            return newFixedLengthResponse(json);
        }
    };


    private LiteWebHttpd.ServletHandler videoListHandler = new LiteWebHttpd.ServletHandler(){

        @Override
        public NanoHTTPD.Response serve(NanoHTTPD.IHTTPSession session) {
            NanoHTTPD.Response r;
            String param = session.getQueryParameterString();
            LogUtils.d(tag,"videoListHandler  param:"+param);
            String url = "http://video.tc.skysrt.com/c/getVideoListByFilterId?"+param;
            String json = JsonParser.getJsonFromWeb(url);
            LogUtils.d(tag,"videoListHandler json:"+json);
            return newFixedLengthResponse(json);
        }
    };

    private LiteWebHttpd.ServletHandler videoDetailHandler = new LiteWebHttpd.ServletHandler(){
        @Override
        public NanoHTTPD.Response serve(NanoHTTPD.IHTTPSession session) {
            NanoHTTPD.Response r;
            String param = session.getQueryParameterString();
            LogUtils.d(tag,"videoDetailHandler  param:"+param);
            String url = "http://video.tc.skysrt.com/v/getVideoDetail?"+param;
            String json = JsonParser.getJsonFromWeb(url);
            LogUtils.d(tag,"videoDetailHandler json:"+json);
//            Map<String, String> parmas = session.getParms();
            return newFixedLengthResponse(json);
        }
    };

    private LiteWebHttpd.ServletHandler videoSearchHandler = new LiteWebHttpd.ServletHandler(){

        @Override
        public NanoHTTPD.Response serve(NanoHTTPD.IHTTPSession session) {
            NanoHTTPD.Response r;
            String param = session.getQueryParameterString();
            LogUtils.d(tag,"videoSearchHandler  param:"+param);
            String url = "http://video.tc.skysrt.com/s/getVideoListByKeyWord?"+param;
            String json = JsonParser.getJsonFromWeb(url);
            LogUtils.d(tag,"videoSearchHandler json:"+json);
            return newFixedLengthResponse(json);
        }
    };


    private LiteWebHttpd.ServletHandler appCategoryHandler = new LiteWebHttpd.ServletHandler(){
        @Override
        public NanoHTTPD.Response serve(NanoHTTPD.IHTTPSession session) {
            NanoHTTPD.Response r;
            String param = session.getQueryParameterString();
            LogUtils.d(tag,"appCategoryHandler  param:"+param);
            String url = "http://tc.skysrt.com/appstore/index.html?"+param;
            String json = getWebDataFromDB(url);
            if(json.equals("")) {
                json = JsonParser.getJsonFromWeb(url);
                saveWebData(url,json);
            }
            LogUtils.d(tag,"appCategoryHandler json:"+json);
//            Map<String, String> parmas = session.getParms();
            return newFixedLengthResponse(json);
        }
    };

    private LiteWebHttpd.ServletHandler appListHandler = new LiteWebHttpd.ServletHandler(){

        @Override
        public NanoHTTPD.Response serve(NanoHTTPD.IHTTPSession session) {
            NanoHTTPD.Response r;
            String param = session.getQueryParameterString();
            LogUtils.d(tag,"appListHandler  param:"+param);
            String url = "http://tc.skysrt.com/appstore/index.html?"+param;
            AppListObject alo = null;
            if (cache.get(url) != null){
                alo = (AppListObject)cache.get(url);
            }else{
                String json = getWebDataFromDB(url);
                if(json.equals("")) {
                    json = JsonParser.getJsonFromWeb(url);
                    if(url.contains("&pageindex=1&"))
                        saveWebData(url,json);
                }
                LogUtils.d(tag, "appListHandler json:" + json);
                if (!json.equals("")){
                    alo = AppListObject.parseJObject(json,AppListObject.class);
                    for (final AppListObject.AppListItem item : alo.data){
                        String temp = ImageCache.getCacheImage(WebDataServlet.this,item.packagename);
                        if (temp != null){
                            item.lmg = temp;
                        }else{
                            AsyncTask.runOnThread(new Runnable() {
                                @Override
                                public void run() {
                                    ImageCache.cacheImage(WebDataServlet.this,item.packagename,item.lmg);
                                }
                            });
                        }

                    }
                    cache.put(url,alo);
                }else{
                    return newFixedLengthResponse(null);
                }
            }
            return newFixedLengthResponse(alo.toJSONString());
        }
    };

    private LiteWebHttpd.ServletHandler searchAppHandler = new LiteWebHttpd.ServletHandler(){

        @Override
        public NanoHTTPD.Response serve(NanoHTTPD.IHTTPSession session) {
            NanoHTTPD.Response r;
            String param = session.getQueryParameterString();
            LogUtils.d(tag,"searchAppHandler  param:"+param);
            String url = "http://tc.skysrt.com/appstore/index.html?"+param;
            ParserData.AppSearchListObject alo = null;
            if (cache.get(url) != null){
                alo = (ParserData.AppSearchListObject)cache.get(url);
            }else{
                String json = JsonParser.getJsonFromWeb(url);
                LogUtils.d(tag, "searchAppHandler json:" + json);
                if (!json.equals("")){
                    alo = ParserData.AppSearchListObject.parseJObject(json, ParserData.AppSearchListObject.class);
                    for (final ParserData.AppSearchListObject.AppSearchItem item : alo.list){
                        String temp = ImageCache.getCacheImage(WebDataServlet.this,item.packagename);
                        if (temp != null){
                            item.lmg = temp;
                        }else{
                            AsyncTask.runOnThread(new Runnable() {
                                @Override
                                public void run() {
                                    ImageCache.cacheImage(WebDataServlet.this,item.packagename,item.lmg);
                                }
                            });
                        }
                    }
                    cache.put(url,alo);
                }else{
                    return newFixedLengthResponse(null);
                }
            }
            return newFixedLengthResponse(alo.toJSONString());
        }
    };

    private LiteWebHttpd.ServletHandler appDetailHandler = new LiteWebHttpd.ServletHandler(){

        private AppDetailObject getAppDetail(String json){
            AppDetailObject ado = AppDetailObject.parseJObject(json, AppDetailObject.class);
            AppDetailObject.AppDetailItem item = ado.details;
            System.out.println(item.packageName+" "+item.title+" "+item.id);
            return ado;
        }

        @Override
        public NanoHTTPD.Response serve(NanoHTTPD.IHTTPSession session) {
            String param = session.getQueryParameterString();
            LogUtils.d(tag,"appDetailHandler  param:"+param);
            String url = "http://tc.skysrt.com/appstore/index.html?"+param;
            String json = JsonParser.getJsonFromWeb(url);
            LogUtils.d(tag,"appDetailHandler json:"+json);
//            AppDetailData data = JsonParser.getAppDetail(json);
//            LogUtils.d(tag,"appDetailHandler data.iconUrl:"+data.iconUrl);
//            String iconCache = ImageCache.cacheImage(WebDataServlet.this,data.iconUrl,data.iconUrl);
//            String[] screenshots = data.screenShots;
//            for(String screenurl : screenshots)
//            {
//                iconCache +="\n"+ ImageCache.cacheImage(WebDataServlet.this,screenurl,screenurl);
//            }
//            LogUtils.d(tag,"appDetailHandler iconCache:"+iconCache);
            AppDetailObject data = getAppDetail(json);
            return newFixedLengthResponse(data.toJSONString());
        }
    };

    private LiteWebHttpd.ServletHandler appDownloadHandler = new LiteWebHttpd.ServletHandler(){
        @Override
        public NanoHTTPD.Response serve(NanoHTTPD.IHTTPSession session) {
//            NanoHTTPD.Response r;
            Map<String ,String > paramMap = session.getParms();
            String downloadUrl = paramMap.get("url");
            if(downloadUrl != null && !downloadUrl.equals("")) {
                LogUtils.d(tag,"appDownloadHandler downloadUrl:"+downloadUrl);
                FileDownload.downLoadApp(WebDataServlet.this, downloadUrl);
            }

//            FileDownload.downLoadApp("http://apk.sky.fs.skysrt.com/uploads/20150821/20150821170745737169.apk");
//            FileDownload.downLoadApp("http://apk.sky.fs.skysrt.com/uploads/20150821/20150821170413896053.apk");

            return null;
        }
    };


    @Override
    public void startDownload(String url) {
        LogUtils.d(tag,"appDownloadHandler startDownload url:"+url);
    }

    @Override
    public void onDownloading(String url, int percent) {
        LogUtils.d(tag,"appDownloadHandler onDownloading url:"+url+" percent:"+percent);
    }

    @Override
    public void finishDownload(String url, String savePath) {
        LogUtils.d(tag, "appDownloadHandler finishDownload url:" + url + " savePath:" + savePath);
        try {
            InstallParams params = new InstallParams();
            params.setFrom(InstallParams.INSTALL_FROM.COOCAA_MARKET);
            XServiceManager.getLitePMService().install(savePath, true, params);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }


    private String getWebDataFromDB(String url)
    {
        String values = "";
        try {
            WebDataDB wData = new WebDataDB();
            List<LiteDBSupport> list = wData.select(null, null, null, "url_key = ?", url);
            if(list != null && list.size() > 0)
            {
                WebDataDB data = (WebDataDB)list.get(0);
                values = data.v;
            }
        }catch(Exception e)
        {
            e.printStackTrace();
        }
        LogUtils.d(tag, "getWebDataFromDB  values:"+values);
        return values;
    }

    private void saveWebData(String url,String values)
    {
          try{
              WebDataDB wData = new WebDataDB();
              wData.delete("url_key = ?", url);
              LogUtils.d(tag, "saveWebData  delete db success!");
              wData.setData(url, values);
              wData.insert();
              LogUtils.d(tag, "saveWebData  insert db success! url:" + url);
              LogUtils.d(tag, "saveWebData  insert db success! values:"+values);
          }catch(Exception e){
              e.printStackTrace();
          }
    }
}
